package org.javaboy.ai.service.impl;

import org.javaboy.ai.domain.WxLogin;
import org.javaboy.ai.mapper.WxLoginMapper;
import org.javaboy.ai.service.IWxLoginService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.javaboy.common.config.MpProperties;
import org.javaboy.common.constant.CacheConstants;
import org.javaboy.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author javaboy
 * @since 2024-07-03
 */
@Service
@EnableConfigurationProperties(MpProperties.class)
public class WxLoginServiceImpl extends ServiceImpl<WxLoginMapper, WxLogin> implements IWxLoginService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    MpProperties mpProperties;

    @Autowired
    RedisCache redisCache;

    @Override
    public WxLogin login(String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("js_code", code);
        params.put("appid", mpProperties.getAppid());
        params.put("secret", mpProperties.getSecret());
        WxLogin wxLogin = restTemplate.getForObject(mpProperties.getTokenUrl(), WxLogin.class, params);
        if (wxLogin.getErrmsg() == null || (wxLogin.getOpenid() != null && wxLogin.getOpenid().length() > 0)) {
            //成功，将获取到的 openid 存入数据库和 Redis
            save(wxLogin);
            wxLogin.setSessionKey(UUID.randomUUID().toString());
            save2Redis(wxLogin);
        }
        return wxLogin;
    }

    private void save2Redis(WxLogin wxLogin) {
        redisCache.setCacheObject(CacheConstants.WX_LOGIN_PREFIX + wxLogin.getSessionKey(), wxLogin, 60, TimeUnit.MINUTES);
    }
}
